﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.PowerPoint;
using System.IO;
using System.Diagnostics;

namespace CommonLibrary.Office
{
    public interface IOfficeHelper : IDisposable
    {
        string Extension { get; }

        void Save();
    }

    public class PowerPoint : IOfficeHelper
    {
        #region Private Fields

        private Application App { get; set; }
        private Presentation Presentation { get; set; }

        #endregion

        #region Properties

        public string Extension { get { return ".ppt"; } }

        #endregion

        #region Constructor

        public PowerPoint(string fileName, string path)
        {
            App = new Application();
            Presentation = App.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);

            if (!fileName.EndsWith(Extension))
            {
                fileName += Extension;
            }
            Presentation.SaveAs(Path.Combine(path, fileName), PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
        }

        #endregion

        #region Methods

        public void AddTextSlide(string text)
        {
            Slide slide = Presentation.Slides.Add(Presentation.Slides.Count + 1, PpSlideLayout.ppLayoutBlank);
            slide.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, 10, 10, 500, 500);
            slide.Shapes[1].TextFrame.TextRange.Text = text;
            Save();
        }

        public void Save()
        {
            Presentation.Save();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (Presentation != null)
            {
                Presentation.Close();
            }

            if (App != null)
            {
                App.Quit();
            }

            App = null;
            Presentation = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        #endregion
    }
}
